<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI选股系统 - 收益分析</title>
    <script src="/static/lib/js/vue.global.js"></script>
    <script src="/static/lib/js/axios.min.js"></script>
    <script src="/static/lib/js/chart.js"></script>
    <link href="/static/lib/css/all.min.css" rel="stylesheet">
    <link href="/static/base.css" rel="stylesheet">
    <link href="/static/components.css" rel="stylesheet">
    <link href="/static/pages.css" rel="stylesheet">
    <link href="/static/utilities.css" rel="stylesheet">
    <link href="/static/optimized-table-styles.css" rel="stylesheet">
    <link href="/static/css/common.css" rel="stylesheet">
</head>
<body>
    <div id="app">
        <div class="app-container">
            <!-- 头部 -->
            <div class="header">
                <div class="header-nav">
                    <h1><i class="fas fa-chart-line"></i> 收益分析</h1>
                    <div class="header-nav-links">
                        <!-- 导航将由JavaScript动态生成 -->
                    </div>
                </div>
                <p>分析选股策略的后续表现，包括收益率、回撤、夏普比率等关键指标</p>
                <div class="header-stats performance-header-stats">
                    <div class="stat-item">
                        <div class="stat-number">{{ performanceResults.length }}</div>
                        <div class="stat-label">分析股票</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ summaryStats ? summaryStats.avg_return.toFixed(2) : '0.00' }}%</div>
                        <div class="stat-label">平均收益率</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ summaryStats ? summaryStats.win_rate.toFixed(1) : '0.0' }}%</div>
                        <div class="stat-label">胜率</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">{{ summaryStats ? summaryStats.valid_stocks : '0' }}</div>
                        <div class="stat-label">有效股票</div>
                    </div>
                </div>
            </div>

            <!-- 主内容区域 -->
            <div class="main-content">
                <div class="tab-content performance-tab-content">
                    <!-- 左侧：分析参数设置面板 -->
                    <div class="control-panel panel performance-control-panel">
                        <div class="panel-title">
                            <i class="fas fa-cog"></i>
                            分析参数设置
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">执行日期</label>
                            <select v-model="executionDate" class="form-control">
                                <option v-for="date in availableDates" :key="date" :value="date">
                                    {{ formatDate(date) }}
                                </option>
                            </select>
                            <div v-if="availableDates.length === 0" class="form-help">
                                <i class="fas fa-info-circle"></i>
                                暂无可用的执行日期，请先在专业版页面执行选股
                            </div>
                            <div v-else class="form-help">
                                <i class="fas fa-info-circle"></i>
                                请选择有后续价格数据的执行日期进行收益分析
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">策略类型</label>
                            <select v-model="selectedStrategy" class="form-control">
                                <option value="">全部策略</option>
                                <option v-for="s in strategies" :key="s[0]" :value="s[0]">
                                    {{ s[1] }}
                                </option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">分析天数</label>
                            <select v-model="analysisDays" class="form-control">
                                <option value="5">5个交易日</option>
                                <option value="10">10个交易日</option>
                                <option value="20">20个交易日</option>
                                <option value="30">30个交易日</option>
                            </select>
                        </div>
                        
                        <button @click="analyzePerformance" :disabled="loading" class="btn btn-primary">
                            <i v-if="loading" class="fas fa-spinner fa-spin"></i>
                            <i v-else class="fas fa-chart-bar"></i>
                            {{ loading ? '分析中...' : '开始分析' }}
                        </button>
                    </div>

                    <!-- 右侧：结果展示面板 -->
                    <div class="results-panel panel performance-results-panel">
                        <div class="panel-title">
                            <i class="fas fa-chart-line"></i>
                            收益分析结果
                        </div>
                        
                        <div class="results-content">
                            <div v-if="loading" class="loading">
                                <i class="fas fa-spinner fa-spin"></i> 正在分析选股表现，请稍候...
                            </div>
                            
                            <!-- 结果表格 -->
                            <div class="table-container performance-table-container">
                                <div v-if="performanceResults.length > 0" class="table-info">
                                    <p>共找到 {{ performanceResults.length }} 条记录</p>
                                </div>
                                <table class="results-table performance-table">
                                    <thead>
                                        <tr>
                                            <th>执行日期</th>
                                            <th>证券代码</th>
                                            <th>证券名称</th>
                                            <th>策略类型</th>
                                            <th>选股价格</th>
                                            <th>最新价格</th>
                                            <th>收益率</th>
                                            <th>振幅</th>
                                            <th>夏普比率</th>
                                            <th>最大回撤</th>
                                            <th>波动率</th>
                                            <th>日胜率</th>
                                            <th>分析天数</th>
                                            <th>数据状态</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="result in filteredResults" :key="result.security_id">
                                            <td>{{ executionDate }}</td>
                                            <td>{{ result.security_id }}</td>
                                                                                         <td>
                                                 <a :href="`/kline?id=${result.security_id}&name=${encodeURIComponent(result.security_name || result.security_id)}`" target="_blank" class="stock-link">
                                                     {{ result.security_name || result.security_id }}
                                                 </a>
                                             </td>
                                            <td>{{ strategyCn(result.strategy_type) }}</td>
                                            <td>{{ result.initial_price ? result.initial_price.toFixed(3) : '-' }}</td>
                                            <td>{{ result.final_price ? result.final_price.toFixed(3) : '-' }}</td>
                                            <td :class="result.return_rate >= 0 ? 'positive' : 'negative'">
                                                {{ result.return_rate ? result.return_rate.toFixed(2) + '%' : '-' }}
                                            </td>
                                            <td>{{ result.amplitude ? result.amplitude.toFixed(2) + '%' : '-' }}</td>
                                            <td :class="result.sharpe_ratio >= 0 ? 'positive' : 'negative'">
                                                {{ result.sharpe_ratio ? result.sharpe_ratio.toFixed(2) : '-' }}
                                            </td>
                                            <td :class="result.max_drawdown <= 0 ? 'positive' : 'negative'">
                                                {{ result.max_drawdown ? result.max_drawdown.toFixed(2) + '%' : '-' }}
                                            </td>
                                            <td>{{ result.volatility ? result.volatility.toFixed(2) + '%' : '-' }}</td>
                                            <td>{{ result.win_rate_daily ? result.win_rate_daily.toFixed(1) + '%' : '-' }}</td>
                                            <td>{{ result.analysis_days || 0 }}</td>
                                            <td>
                                                <span v-if="result.has_future_data" class="status-badge success">
                                                    <i class="fas fa-check-circle"></i> 有效
                                                </span>
                                                <span v-else class="status-badge warning">
                                                    <i class="fas fa-exclamation-triangle"></i> 无后续数据
                                                </span>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <script>
        const { createApp } = Vue;
        
        createApp({
            data() {
                return {
                    executionDate: new Date().toISOString().split('T')[0], // 已经是YYYY-MM-DD格式
                    availableDates: [],
                    strategies: [],
                    strategyPairs: [], // 来自 /api/strategies 的 [英文, 中文]
                    selectedStrategy: '',
                    analysisDays: 20,
                    performanceResults: [],
                    summaryStats: null,
                    loading: false,
                    message: '',
                    messageType: 'success',
                    stockFilter: ''
                }
            },
            
            computed: {
                filteredResults() {
                    if (!this.stockFilter) return this.performanceResults;
                    return this.performanceResults.filter(result => 
                        result.security_id.toLowerCase().includes(this.stockFilter.toLowerCase()) ||
                        (result.security_name && result.security_name.toLowerCase().includes(this.stockFilter.toLowerCase()))
                    );
                }
            },
            
            async mounted() {
                await this.loadAvailableData();
            },
            
            methods: {
                async loadAvailableData() {
                    try {
                        const response = await axios.get('/api/available-data');
                        if (response.data.success) {
                            const data = response.data.data;
                            this.availableDates = data.available_dates || [];
                            const availableEn = data.available_strategies || [];
                            // 获取完整策略对照表
                            try {
                                const res2 = await axios.get('/api/strategies');
                                if (res2.data && res2.data.success) {
                                    this.strategyPairs = res2.data.data.strategies || [];
                                } else {
                                    this.strategyPairs = [];
                                }
                            } catch(e){ this.strategyPairs = []; }
                            // 将可用英文策略映射为 [英文, 中文]
                            const dict = new Map((this.strategyPairs||[]).filter(x=>Array.isArray(x) && x.length>=2));
                            this.strategies = availableEn.map(en => [en, dict.get(en) || en]);
                            
                            // 如果有可用的执行日期，选择较早的日期（有后续价格数据）
                            if (this.availableDates.length > 0) {
                                // 选择最后一个日期（较早的日期）
                                this.executionDate = this.availableDates[this.availableDates.length - 1];
                            }

                        }
                    } catch (error) {
                        this.showMessage('加载可用数据失败', 'error');
                        console.error('加载可用数据失败:', error);
                    }
                },
                
                async loadStrategies() {
                    try {
                        const response = await axios.get('/api/strategies');
                        if (response.data.success) {
                            // 保持 [英文, 中文] 结构，便于直接展示中文
                            this.strategies = response.data.data.strategies;
                        }
                    } catch (error) {
                        this.showMessage('加载策略列表失败', 'error');
                    }
                },
                
                async analyzePerformance() {
                    this.loading = true;
                    this.message = '';
                    
                    try {
                        const response = await axios.post('/api/performance-analysis', {
                            execution_date: this.executionDate,
                            strategy_type: this.selectedStrategy,
                            analysis_days: parseInt(this.analysisDays)
                        });
                        
                        if (response.data.success) {
                            this.performanceResults = response.data.data.results;
                            this.summaryStats = response.data.data.summary;
             
                            this.showMessage(`分析完成，共分析 ${this.performanceResults.length} 只股票`, 'success');
                        } else {
                            this.showMessage(response.data.error, 'error');
                        }
                    } catch (error) {
                        this.showMessage('分析失败: ' + error.message, 'error');
                    } finally {
                        this.loading = false;
                    }
                },
                
                showMessage(text, type = 'success') {
                    this.message = text;
                    this.messageType = type;
                    setTimeout(() => {
                        this.message = '';
                    }, 5000);
                },
                
                exportResults() {
                    if (this.performanceResults.length === 0) {
                        alert('没有可导出的结果');
                        return;
                    }
            
                },
                
                getStatusIcon() {
                    switch (this.messageType) {
                        case 'success':
                            return 'fas fa-check-circle';
                        case 'warning':
                            return 'fas fa-exclamation-triangle';
                        case 'error':
                            return 'fas fa-times-circle';
                        default:
                            return 'fas fa-info-circle';
                    }
                },
                
                formatDate(dateString) {
                    if (!dateString) return '';
                    const date = new Date(dateString);
                    return date.toLocaleDateString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit'
                    });
                },

                strategyCn(name){
                    if (!name) return '';
                    // 优先用 strategyPairs 建表，兼容 this.strategies 为字符串/数组
                    const pairs = (this.strategyPairs && this.strategyPairs.length) ? this.strategyPairs : this.strategies;
                    const entries = (pairs||[]).filter(x=>Array.isArray(x) && x.length>=2);
                    const m = new Map(entries);
                    return m.get(name) || name;
                }
            }
        }).mount('#app');
    </script>
    
    <!-- 公共JavaScript库 -->
    <script src="/static/js/common.js"></script>
    <script src="/static/js/navigation.js"></script>
</body>
</html>
